package net.es.lookup.scalability.testing;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: luke
 * Date: 8/30/13
 * Time: 12:59 PM
 * To change this template use File | Settings | File Templates.
 */
public class OutputWriter {

    //collect output from messenger threads into a single data structure

    //print aggregated output to a single target (file if named, stdout if no file provided)

    private static ArrayList<String> results;

    /*public OutputWriter() {

        results = new ArrayList<String>();
    }*/

    static {

        results = new ArrayList<String>();
    }

    public static synchronized void add(String threadOutput) {

        results.add(threadOutput);
    }

    public static void print(String fileBase) {

        PrintWriter pw = null;

        try {

            if (fileBase != null) {

                DateFormat df = new SimpleDateFormat("MM-dd_HH:mm:ss");
                long testStart = System.currentTimeMillis();
                String timestamp = df.format(testStart);

                File f = new File(fileBase + "_" + timestamp);
                f.createNewFile();

                pw = new PrintWriter(new FileWriter(f));
            } else {

                pw = new PrintWriter(System.out);
            }

            for (String r : results) {

                pw.println(r);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pw.close();
        }
    }
}
